package com.controller.dept;

import com.common.ErrorCodeEnum;
import com.model.base.PageResult;
import com.model.base.Result;
import com.common.anntation.Log;
import com.common.emums.BusinessType;
import com.common.emums.DataStatus;

import com.common.exception.BusinessException;
import com.common.utils.EntityConversionUtil;
import com.common.utils.StringUtils;
import com.core.springSecurity.service.PermissionService;
import com.model.dto.sys.Dept.CreateDeptDTO;
import com.model.dto.sys.Dept.GetDeptListDTO;
import com.model.dto.sys.Dept.UpdateDeptDTO;
import com.model.dto.sys.Dept.UpdateDeptStatusDTO;
import com.github.pagehelper.PageInfo;
import com.model.pojo.sys.SysDept;
import com.service.sys.SysDeptService;
import com.service.sys.SysUserService;
import com.model.vo.sys.dept.DeptVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * @Author: zql
 * @Description: 部门管理服务
 * @Data: 10:45 2021/5/12
 */
@Api(tags = {"部门"})
@Slf4j
@RestController
@RequestMapping("/v1")
public class DeptController {
    @Resource
    SysDeptService sysDeptService;

    @Resource
    SysUserService sysUserService;

    /**
     * @param createDeptDTO 创建部门参数
     * @Author: zql
     * @Description: 创建部门
     * @Data: 12:09 2021/5/12
     */
    @ApiOperation(value = "创建部门")
    @Log(title = "创建部门", businessType = BusinessType.INSERT)
    @PostMapping("/createDept")
    public Result<Objects> createDept(@RequestBody @Valid CreateDeptDTO createDeptDTO) {
        SysDept dept = EntityConversionUtil.copy(createDeptDTO, SysDept.class);
        if (sysDeptService.hasName(dept.getDeptName(), DataStatus.OK.getCode())) {
            throw new BusinessException(ErrorCodeEnum.DEPT_NAME_EXISTS);
        }
        sysDeptService.create(dept);
        return Result.suc();
    }

    /**
     * @param updateDeptDTO 修改部门参数
     * @Author: zql
     * @Description: 修改部门信息
     * @Data: 12:12 2021/5/12
     */
    @ApiOperation(value = "更新部门信息")
    @Log(title = "更新部门信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updateDept")
    @PreAuthorize("@ss.hasAnyPermi('" + PermissionService.SYSTEM_OPERATE + "')")
    public Result<Objects> updateDept(@RequestBody @Valid UpdateDeptDTO updateDeptDTO) {
        SysDept sysDept = sysDeptService.get(updateDeptDTO.getSysDeptId(), null);
        BeanUtils.copyProperties(updateDeptDTO, sysDept);
        if (StringUtils.isNotNull(updateDeptDTO.getDeptName()) && !sysDept.getDeptName().equals(updateDeptDTO.getDeptName()) && sysDeptService.hasName(updateDeptDTO.getDeptName(), DataStatus.OK.getCode())) {
            throw new BusinessException(ErrorCodeEnum.DEPT_NAME_EXISTS);
        }
        sysDeptService.update(sysDept);
        return Result.suc();
    }

    @ApiOperation(value = "修改部门状态")
    @Log(title = "修改部门状态", businessType = BusinessType.UPDATE)
    @PostMapping("/updateDeptStatus")
    @PreAuthorize("@ss.hasAnyPermi('" + PermissionService.SYSTEM_OPERATE + "')")
    public Result<Objects> updateDeptStatus(@RequestBody @Valid UpdateDeptStatusDTO updateDeptStatusDTO) {
        if (1 == updateDeptStatusDTO.getSysDeptId()) {
            throw new BusinessException(ErrorCodeEnum.FATHER_DEPT);
        }
        SysDept sysDeptDb = sysDeptService.get(updateDeptStatusDTO.getSysDeptId(), null);
        boolean sysDeptDTOOk = DataStatus.OK.equals(updateDeptStatusDTO.getIsDelete());
        boolean sysDeptDTODisable = DataStatus.DISABLE.equals(updateDeptStatusDTO.getIsDelete());
        boolean sysDeptDTODelete = DataStatus.DELETED.equals(updateDeptStatusDTO.getIsDelete());
        boolean deptDbOk = DataStatus.OK.equals(sysDeptDb.getIsDelete());

        if (sysDeptDTOOk && !deptDbOk) {
            if (sysDeptService.hasName(sysDeptDb.getDeptName(), DataStatus.OK.getCode())) {
                throw new BusinessException(ErrorCodeEnum.DEPT_NAME_EXISTS);
            }
        }
        if (deptDbOk && (sysDeptDTODisable || sysDeptDTODelete)){
            if (sysUserService.hasDept(updateDeptStatusDTO.getSysDeptId())) {
                throw new BusinessException(ErrorCodeEnum.DEPT_USER);
            }
            if(sysDeptService.hasChild(updateDeptStatusDTO.getSysDeptId(),DataStatus.OK.getCode())){
                throw new BusinessException(ErrorCodeEnum.DEPT_CHILD);
            }
        }
        SysDept sysDept = new SysDept();
        sysDept.setSysDeptId(updateDeptStatusDTO.getSysDeptId());
        sysDept.setIsDelete(updateDeptStatusDTO.getIsDelete());
        sysDeptService.update(sysDept);
        return Result.suc();
    }

    /**
     * @param getDeptListDTO 查看部门参数
     * @Author: zql
     * @Description: 查看部门列表
     * @Data: 16:51 2021/7/2
     */
    @ApiOperation(value = "查询部门列表")
    @Log(title = "查询部门列表", businessType = BusinessType.SELECT, isSaveResponseData = false)
    @PostMapping("/getDeptList")
    @PreAuthorize("@ss.hasAnyPermi('" + PermissionService.SYSTEM_OPERATE + "')")
    public Result<PageResult<List<DeptVO>>> getDeptList(@RequestBody @Valid GetDeptListDTO getDeptListDTO) {
        List<SysDept> sysDeptList = sysDeptService.getDeptList(getDeptListDTO.getSysDeptId(), getDeptListDTO);
        PageInfo<SysDept> pageInfo = new PageInfo<>(sysDeptList);
        List<DeptVO> deptVOList = EntityConversionUtil.copyList(sysDeptList, DeptVO.class);
        deptVOList.forEach(deptVO -> {
            deptVO.setUserCount(sysUserService.getCountByDeptId(deptVO.getSysDeptId()));
        });
        PageResult<List<DeptVO>> build = PageResult.<List<DeptVO>>builder().result(deptVOList).pageInfo(pageInfo).build();
        return Result.suc(build);
    }
}
